import { staticRoutes,allSyncRoutes,anyRoute } from '@/router/routes'
import {defineStore} from 'pinia'
import userInfoApi,{type LoginParamsData, type UserInfoData} from '@/api/userInfo'
import type { RouteRecordRaw } from 'vue-router'
import router from '@/router'
import cloneDeep from 'lodash/cloneDeep'

interface UserStoreStateData {
    token:string,
    userInfo:UserInfoData,
    menuRoutes:RouteRecordRaw[]
  }

  function filterRoutes(allSyncRoutes:RouteRecordRaw[],routesName:string[]){
    let result =allSyncRoutes.filter(item=>{
      if (routesName.indexOf(item.name as string)!==-1) {
        if (item.children) {
          item.children=filterRoutes(item.children,routesName)
        }
        return true
      }
    })
    return result
  }
  
  function addRoutes(routes:RouteRecordRaw[]){
    routes.forEach(item=>{
      router.addRoute(item)
    })
  }
  
  function routeSet(){
    let result=router.getRoutes()
    result.forEach(item=>{
      router.removeRoute(item.name as string)
    })
    addRoutes(staticRoutes)
  }
export const useUserInfoStore=defineStore('userInfo',{
    state():UserStoreStateData {
        return{
            token:localStorage.getItem('token_key') || '',
            userInfo:{
                name:'',
                avatar:'',
                routes:[],
                buttons:[],
                roles:[]
            },
            menuRoutes:staticRoutes
        }
    },
    actions:{
        async login(loginParams:LoginParamsData){
            try {
              const result = await userInfoApi.userLogin(loginParams)
              this.token = result.token
              localStorage.setItem('token_key',result.token)
              return 'ok'
            } catch (error) {
              return Promise.reject(error)
            }
          },
        async getUserInfo(){
            try {
                const result = await userInfoApi.getUserInfo()
                this.userInfo = result
                let newRoutes=filterRoutes(cloneDeep(allSyncRoutes),result.routes)
                addRoutes(newRoutes.concat(anyRoute))
                this.menuRoutes=staticRoutes.concat(allSyncRoutes,anyRoute)
                return 'ok'
              } catch (error) {
                return Promise.reject(error)
              }
        },
        async reset(){
            this.token = ''
            this.userInfo = {
              name:'',
              avatar:'',
              routes:[],
              buttons:[],
              roles:[]
            }
            
            localStorage.removeItem('token_key')
          },
      
          async logout(){
            try {
              await userInfoApi.userLogout()
              this.reset()
              routeSet()
              return 'ok'
            } catch (error) {
              return Promise.reject(error)
            }
          }
    },
    getters:{}
})